package com.aigc.sclassroom.controller;

import com.aigc.sclassroom.pojo.*;
import com.aigc.sclassroom.service.HomeworkService;
import com.aigc.sclassroom.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/homework")
public class HomeworkController {
    @Autowired
    private HomeworkService homeworkService;

    //获取该课程所有作业，包括内容
    @GetMapping("/getAll")
    public Result<List<Homework>> getHomeworkAll(@RequestParam Long courseManageId) {
        List<Homework> hs = homeworkService.selectAll(courseManageId);
        for (int i = 0; i < hs.size(); i++) {
           String[] q = homeworkService.selectQuestion(hs.get(i).getHomeworkId());
           String[] a = homeworkService.selectAnswer(hs.get(i).getHomeworkId());
           Long[] ids = homeworkService.selectId(hs.get(i).getHomeworkId());
           int[] s = homeworkService.selectScoreSet(hs.get(i).getHomeworkId());
           int sum = homeworkService.selectSum(courseManageId);
           int submitCount = homeworkService.selectSubmitCount(hs.get(i).getHomeworkId());
            hs.get(i).setQuestion(q);
            hs.get(i).setQuestionId(ids);
            hs.get(i).setAnswer(a);
            hs.get(i).setScoreSet(s);
            hs.get(i).setSum(sum);
            hs.get(i).setSubmitCount(submitCount);
        }

        return Result.success(hs);
    }

    //学生获取课程所有作业，不包括答案和提交人数
    @GetMapping("/stuGetAll")
    public Result<List<Homework>> stuGetHomeworkAll(@RequestParam Long courseManageId) {
        List<Homework> hs = homeworkService.selectAll(courseManageId);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        Long userId =(id.longValue());
        for (int i = 0; i < hs.size(); i++) {
            String[] q = homeworkService.selectQuestion(hs.get(i).getHomeworkId());
            Long[] ids = homeworkService.selectId(hs.get(i).getHomeworkId());
            int[] s = homeworkService.selectScoreSet(hs.get(i).getHomeworkId());
            hs.get(i).setQuestion(q);
            hs.get(i).setQuestionId(ids);
            hs.get(i).setScoreSet(s);
            List<Long> studentAnswerIds = homeworkService.selectStuAnswerId(userId,hs.get(i).getHomeworkId());
            Integer totalScore = homeworkService.selectTotalScore(hs.get(i).getHomeworkId(),userId);
            hs.get(i).setTotalScore(totalScore);
            if(hs.get(i).getState().equals("已截止")){
                continue;
            }
            if (studentAnswerIds != null && !studentAnswerIds.isEmpty()){
                hs.get(i).setState("已提交");
                Integer score = homeworkService.selectScore(studentAnswerIds.get(0));
                if (score!=null){
                    hs.get(i).setState("已批改");
                }
            }else {
                hs.get(i).setState("待提交");
            }
        }
        return Result.success(hs);
    }

    //发布作业及其内容
    @PostMapping("/addHomework")
    public Result addHomework(@RequestBody Homework homework) {
        try {
            homeworkService.addHomework(homework);
            List<Homework> hs = homeworkService.selectAll(homework.getCourseManageId());
            Long homeworkId = null;
            for (int i = 0; i < hs.size(); i++) {
                if (hs.get(i).getHomeworkName().equals(homework.getHomeworkName()) &&
                        hs.get(i).getCourseManageId()==homework.getCourseManageId()) {
                    homeworkId = hs.get(i).getHomeworkId();
                    break; // 一旦找到匹配的作业ID，就可以跳出循环
                }
            }
            if (homeworkId == null) {
                // 如果homeworkId仍然是null，可能是因为刚刚添加的作业没有检索到（理论上不应该发生，除非数据不一致）
                throw new RuntimeException("Failed to retrieve homework ID after adding homework.");
            }
            homeworkService.addQuestion(homework.getQuestion(), homework.getAnswer(), homework.getScoreSet(),homeworkId);
            return Result.success();
        } catch (DataIntegrityViolationException e) {
            // 假设使用的是Spring框架，DataIntegrityViolationException通常用于表示数据完整性异常
            // 这里可以根据异常的具体信息返回更具体的错误信息给用户
            return Result.error("已存在该作业，若内容不同，请换一个作业名");
        } catch (Exception e) {
            // 捕获其他可能的异常
            System.out.println(e);
            return Result.error("发生未知错误");
        }
    }

    //教师查询学生提交作业情况
    @GetMapping("/getResult")
    public Result<List<HomeworkResult>> getHomeworkResult(@RequestParam Long homeworkId){
        List<HomeworkResult> hs = homeworkService.selectResult(homeworkId);
        return Result.success(hs);
    }

    //教师查询学生填写答案情况(点击批改或查看按钮后拿到数据)
    //需要作业id和学生id
    @GetMapping("/getStuAnswer")
    public Result<List<StuAnswer>> getStuAnswer(@RequestParam Long homeworkId,@RequestParam Long userId){
        List<StuAnswer> ss = homeworkService.selectStuAnswer(homeworkId,userId);
        return Result.success(ss);
    }
    //教师批改学生答案功能实现
    @PutMapping("/updateScore")
    public Result updateScore(@RequestBody List<StuAnswer> list){
        for(StuAnswer stuAnswer : list){
            homeworkService.updateScore(stuAnswer);
        }
        return Result.success();
    }

    //学生提交作业
    @PostMapping("/submitHomework")
    public Result submitHomework(@RequestBody List<Answer> answers) {
        try {
            // 调用服务层方法提交答案
            homeworkService.submitAnswer(answers);
            return Result.success("作业提交成功");
        } catch (DuplicateKeyException e) {
            // 捕获唯一索引约束异常
            return Result.error("作业已提交，请勿重复提交");
        } catch (Exception e) {
            // 捕获其他异常
            return Result.error("作业提交失败：" + e.getMessage());
        }
    }

    //统计数据（作业提交率和平均分）

    @GetMapping("/statistics")
    public Result<List<HomeworkPercent>> homeworkStatistics(@RequestParam Long courseManageId) {
        // 1. 获取课程下的所有作业
        List<Homework> homeworkList = homeworkService.selectAll(courseManageId);
        if (homeworkList == null || homeworkList.isEmpty()) {
            return Result.success(Collections.emptyList()); // 如果作业列表为空，返回空列表
        }
        // 2. 获取总人数（只需查询一次）
        int totalStudents = homeworkService.selectSum(courseManageId);
        if (totalStudents == 0) {
            return Result.success(Collections.emptyList()); // 如果总人数为0，返回空列表
        }
        // 3. 初始化结果列表
        List<HomeworkPercent> homeworkPercents = new ArrayList<>(homeworkList.size());
        // 4. 遍历作业列表，计算提交百分比
        for (Homework homework : homeworkList) {
            Long homeworkId = homework.getHomeworkId();
            int submitCount = homeworkService.selectSubmitCount(homeworkId);
            // 计算提交百分比（保留两位小数）
            double submitPercent = (double) submitCount / totalStudents * 100;
            // 创建 HomeworkPercent 对象并设置值
            HomeworkPercent homeworkPercent = new HomeworkPercent();
            homeworkPercent.setHomeworkId(homeworkId);
            homeworkPercent.setSubmitPercent(submitPercent);
            // 添加到结果列表
            homeworkPercents.add(homeworkPercent);
            // 计算已批改分数平均分
            AverageCount averageCount = homeworkService.selectAverage(homeworkId);
            if (averageCount.getAverageScore()==null){
                averageCount.setAverageScore(0);
            }
            double averageScore = (double) averageCount.getAverageScore() /averageCount.getUserCount();
            homeworkPercent.setAverageScore(averageScore);
        }
        // 5. 返回结果
        return Result.success(homeworkPercents);
    }

}
